//
//  FBDPictureViewController.m
//  iOS9Sample-Photos
//
//  Created by feng on 16/3/7.
//  Copyright © 2016年 小码哥. All rights reserved.
//
#define ScrenWidth [UIScreen mainScreen].bounds.size.width
#define  cellIndentifi @"collectionCells"
#import "FBDPictureViewController.h"
#import "FBDPictureCollectionViewCell.h"
#import "FBDPhotoBrowseViewController.h"
#import "FBDPhotoManger.h"


@interface FBDPictureViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong)UICollectionView* collectionView;
@end

@implementation FBDPictureViewController
{
    NSTimer* myReloadTimer;
    NSString* tempChage;
}
-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    

    
    
    
}



-(instancetype)init
{
    self=[super init];
    
    tempChage=nil;
    CGFloat everyItemWidth=(ScrenWidth-5*7.0)/4;
    
    UICollectionViewFlowLayout*flowLayout=[[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing=5;
    flowLayout.minimumInteritemSpacing=5;
    flowLayout.itemSize=CGSizeMake(everyItemWidth, everyItemWidth);
    flowLayout.sectionInset=UIEdgeInsetsMake(20,7, 20, 7);
    _collectionView=[[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen]bounds] collectionViewLayout:flowLayout];
    _collectionView.backgroundColor=[UIColor brownColor];
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    [_collectionView registerClass:[FBDPictureCollectionViewCell class] forCellWithReuseIdentifier:cellIndentifi];
    [self.view addSubview:_collectionView];
    

    
    return self;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem* rightButtonItem=[[UIBarButtonItem  alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonAction)];
    self.navigationItem.rightBarButtonItem=rightButtonItem;
   

    [_collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
    
    
    
    
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
  
    
    
    if ([keyPath isEqualToString:@"contentSize"]) {
        
        if ([tempChage isEqualToString:[NSString stringWithFormat:@"%@",[change objectForKey:@"new"]]]) {
            return;
        }
        
        if (_fontShow) {
            return;
        }
        NSLog(@"contentSize 监控到了%@",[change objectForKey:@"new"]);
        CGFloat newSize=_collectionView.contentSize.height;
        CGFloat heightF=CGRectGetHeight(_collectionView.frame);

        _collectionView.contentOffset=CGPointMake(0, newSize-heightF);
        tempChage=[NSString stringWithFormat:@"%@",[change objectForKey:@"new"]];
        
    }
    
    
}

-(void)backButtonAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)setPictureListArray:(NSMutableArray *)pictureListArray
{
    if (pictureListArray.count<20) {
        _fontShow=YES;
    }
    _pictureListArray=pictureListArray;
    NSLog(@"setPictureListArrayFor_pictureListArray数量：%ld",_pictureListArray.count);
    
    [_collectionView reloadData];
    

}
#pragma mark ----------UICollectionViewDataSource,UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_pictureListArray.count>0)
    {
        
        return _pictureListArray.count;
    }
    
    return 0;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FBDPictureCollectionViewCell* cell=[collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifi forIndexPath:indexPath];
    NSInteger row=indexPath.row;
    PHAsset*asset=[_pictureListArray objectAtIndex:row];
    
    if ([[FBDPhotoManger shareManager].selectAssetIDPhotoArray containsObject:asset.localIdentifier])
    {
        cell.isSelect=YES;
    }else
    {
        cell.isSelect=NO;
    }
    
        PHImageRequestOptions *imageOptions = [[PHImageRequestOptions alloc] init];
        imageOptions.synchronous = YES;
        imageOptions.deliveryMode=PHImageRequestOptionsDeliveryModeOpportunistic;
        imageOptions.resizeMode=PHImageRequestOptionsResizeModeNone;
        imageOptions.networkAccessAllowed=NO;
        imageOptions.progressHandler=^(double progress, NSError *__nullable error, BOOL *stop, NSDictionary *__nullable info)
        {
            NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>>>>>%f",progress);
            
        };
        // 图片原尺寸
        CGSize targetSize = CGSizeMake(asset.pixelWidth/15.0, asset.pixelHeight/15.0);
        // 请求图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeDefault options:imageOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            NSLog(@"图片：%@ /n info :%@", result,info);
            cell.middeImageView.image=result;
            BOOL isiCloudAsset=NO;
            //根据请求会调中的参数重 NSDictionary *info 是否有cloudKey 来判断是否是  iCloud
            if ([[info objectForKey: PHImageResultIsInCloudKey] boolValue])
            {
                isiCloudAsset = YES;
            }
            NSLog(@"isiCloudAsset:>>>>>>%d",isiCloudAsset);
        }];
        
        
    
    
   

    
    
    
    
    
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row=indexPath.row;
//    PHAsset*asset=[_pictureListArray objectAtIndex:row];
//    NSLog(@"选中的asset的值：%@",asset.localIdentifier);
//   FBDPictureCollectionViewCell*indexcell= (FBDPictureCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
//    indexcell.isSelect=!indexcell.isSelect;
//    if (indexcell.isSelect)
//    {
//        [[FBDPhotoManger shareManager].selectAssetIDPhotoArray addObject:asset.localIdentifier];
//
//    }else{
//        [[FBDPhotoManger shareManager].selectAssetIDPhotoArray removeObject:asset.localIdentifier];
//
//    }
    
    
//    FBDPhotoBrowseViewController* browseVC=[[FBDPhotoBrowseViewController alloc]init];
//    browseVC.browseListArray=_pictureListArray;
//    browseVC.indexNumber=row;
//    [self.navigationController pushViewController:browseVC animated:YES];
    
    NSIndexPath *zhongIndexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    if (indexPath.row==0&&indexPath.section==0)
    {
        return;
    }
    [collectionView moveItemAtIndexPath:indexPath toIndexPath:zhongIndexPath];
    
    
     PHAsset*asset=[_pictureListArray objectAtIndex:indexPath.row];
    [_pictureListArray removeObject:asset];
    [_pictureListArray insertObject:asset atIndex:zhongIndexPath.row];
    
    
    
    

}
/**
 *      @author 冯宝东
 *
 *      最后一次关了定时器
 */
-(void)reloadCollectionView
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
       
        [_collectionView reloadData];
        [myReloadTimer invalidate];
        myReloadTimer=nil;
        
    });
   

}

-(void)timeToRelaodCollectionView
{
    [_collectionView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.



}
-(void)dealloc
{
    [self.collectionView removeObserver:self forKeyPath:@"contentSize"];
    
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
